package httpclint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;

public class CookieDemo {
    public static final String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
    private ThreadLocal<HttpClient> hc = new ThreadLocal<HttpClient>();
	private ThreadLocal<Cookie[]> cookies = new ThreadLocal<Cookie[]>();
	public void createByHttpClientWithCookie(String URLStr)
			throws HttpException, IOException {
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setProxy("172.20.230.5", 3128);
		hc.set(client);
		GetMethod method = getMethodWithCookie(URLStr);
		if (method != null) {
			try {
				InputStreamReader in = new InputStreamReader(method
						.getResponseBodyAsStream());
				System.out.println(inputStream2String(in));
			} finally {
				method.releaseConnection();
			}
		}
	}
	private String inputStream2String(Reader in) throws IOException {
		BufferedReader br = new BufferedReader(in);
		StringBuffer sb = new StringBuffer();
		String s = null;
		while((s = br.readLine()) != null) {
			sb.append(s);
		}
		return sb.toString();
	}
	private GetMethod getMethodWithCookie(String URLStr) throws HttpException,
			IOException {
		GetMethod method = initMethod(URLStr);

//		if (cookies.get() == null) {
//			saveCookies(URLStr);
//		}
		HttpState httpState = new HttpState();
//		Cookie cookie = new Cookie();
//		cookie.setName("visited");
//		cookie.setValue("true");
//		
//		Cookie c2 = new Cookie();
//		c2.setName("b");
//		c2.setValue("d8539a74-7c7f-11e0-9c1a-005056956282");
//		Cookie[] cookies = {cookie,c2};
//		
		String domain = ".groupon.com";
		Cookie c1 = new Cookie(domain, "__utma", "44473723.1693915295.1306196136.1306196136.1306196168.2");
		Cookie c2 = new Cookie(domain, "__utmc", "44473723");
		Cookie c3 = new Cookie(domain, "__utmb", "44473723.12.3.1306196504047");
		Cookie c4 = new Cookie(domain, "b", "7cda8b7a-851d-11e0-9768-00505692531b");
		Cookie c5 = new Cookie(domain, "division", "boston");
		Cookie c6 = new Cookie(domain, "_thepoint", "d243db4c40e0f2bf83e6af5b6ab9ceed");
		Cookie c7 = new Cookie(domain, "visited", "true");
		Cookie c8 = new Cookie(domain, "__utmz", "44473723.1306196136.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)");
		Cookie c9 = new Cookie(domain, "s", "8f692832-851d-11e0-8554-0050569560af");
		Cookie c10 = new Cookie(domain, "_chartbeat2", "15swnpdmaiqkerjp");
		Cookie c11 = new Cookie(domain, "spike_landing_url", "http%3A%2F%2Fwww.groupon.com%2Fboston");
		Cookie c12 = new Cookie("d.groupon.com", "OAID", "3ffce2a5df80663bc39b1d852c1e7509");

		Cookie[] cs = {c11};
		httpState.addCookies(cs);
		hc.get().setState(httpState);
		hc.get().getParams().setCookiePolicy(CookiePolicy.RFC_2109);

		int res = hc.get().executeMethod(method);
		if (res == HttpStatus.SC_OK) {
			return method;
		} else {
			method.releaseConnection();
		}

		return null;
	}

	protected GetMethod initMethod(String url) {
    	String encodeQueryUrl = url;
    	try {
			encodeQueryUrl = URIUtil.encodeQuery(url);
		} catch (URIException e) {}
        GetMethod method = new GetMethod(encodeQueryUrl);
        method.getParams().setParameter(HttpMethodParams.USER_AGENT,
                USER_AGENT);
        method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        return method;
    }
	
	private void saveCookies(String URLStr) throws HttpException, IOException {
		HttpMethod method = initMethod(URLStr);
		int res = hc.get().executeMethod(method);
		if (res == HttpStatus.SC_OK) {
			cookies.set(hc.get().getState().getCookies().clone());
		}
		method.releaseConnection();
	}
	
	public static void main(String[] args) throws HttpException, IOException {
		CookieDemo d = new CookieDemo();
		d.createByHttpClientWithCookie("http://www.groupon.com/boston");
	}
	
}
